package com.codedancer.campus.client.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codedancer.campus.client.service.IHeadlineNewsService;
import com.codedancer.campus.client.service.bo.headlineNews.HeadlineNewsPageSearchBo;
import com.codedancer.campus.client.service.vo.headlineNews.HeadlineNewsPageVo;
import com.codedancer.campus.client.service.vo.headlineNews.HeadlineNewsVo;
import com.codedancer.campus.common.dataresource.ExternalApiData;
import com.codedancer.campus.common.dataresource.TianXinData;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.common.model.xr.LocalNewsModel;
import com.codedancer.campus.common.utils.IpUtils;
import com.codedancer.campus.enums.HeadlineNewsType;
import com.codedancer.campus.mapper.HeadlineNewsMapper;
import com.codedancer.campus.po.HeadlineNews;
import com.codedancer.campus.qo.headlineNews.HeadlineNewsPageSearchQo;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class HeadlineNewsServiceImpl implements IHeadlineNewsService {

    @Autowired
    private HeadlineNewsMapper headlineNewsMapper;
    @Autowired
    private TianXinData tianXinData;
    @Autowired
    private ExternalApiData externalApiData;

    /**
     * 分页查询头条新闻
     *
     * @param headlineNewsPageSearchBo
     * @return
     */
    @Override
    public IPage<HeadlineNewsPageVo> page(HttpServletRequest request,
        HeadlineNewsPageSearchBo headlineNewsPageSearchBo) {
        HeadlineNewsPageSearchQo headlineNewsPageSearchQo = BeanUtil.copyProperties(
            headlineNewsPageSearchBo, HeadlineNewsPageSearchQo.class);
        IPage<HeadlineNewsPageVo> headlineNewsPageVoIPage = new Page<>();
        if (Objects.equals(headlineNewsPageSearchBo.getType(),
            HeadlineNewsType.LOCAL_NEWS.getValue())) {
            // 查询本地新闻，本地新闻根据ip地址查询到当地最新新闻
            // 先去拉取最新的本地新闻
            // 获取ip地址
            String location = tianXinData.getLocationByIp(IpUtils.getIpAddr(request));
            log.info("获取的location：{}", location);
            if (ObjectUtil.isEmpty(location)) {
                return headlineNewsPageVoIPage;
            }
            List<LocalNewsModel> localNewsModels = new ArrayList<>();
            try {
                // 拉取最新本地新闻
                localNewsModels = externalApiData.getLocalNewsData(location);
            } catch (Exception e) {
                log.error("本地新闻数据拉取失败");
            } finally {
                // 保存到数据库中
                for (LocalNewsModel localNewsModel : localNewsModels) {
                    if (headlineNewsMapper.existsByUuId(localNewsModel.getDocid())) {
                        continue;
                    }
                    HeadlineNews headlineNews = HeadlineNews.builder()
                        .uuid(localNewsModel.getDocid())
                        .title(localNewsModel.getTitle())
                        .coverImage(localNewsModel.getImgsrc())
                        .source(localNewsModel.getSource())
                        .publishDate(
                            DateUtil.parse(localNewsModel.getPtime(), "yyyy-MM-dd HH:mm:ss"))
                        .description(localNewsModel.getDigest())
                        .location(location)
                        .url(localNewsModel.getUrl())
                        .type(HeadlineNewsType.LOCAL_NEWS)
                        .build();
                    headlineNewsMapper.insert(headlineNews);
                    headlineNewsPageSearchQo.setLocation(location);
                }
            }
        }
        IPage<HeadlineNews> headlineNewsIPage = headlineNewsMapper.page2Client(
            new Page<HeadlineNews>(headlineNewsPageSearchBo.getPage(),
                headlineNewsPageSearchBo.getSize()), headlineNewsPageSearchQo);
        List<HeadlineNewsPageVo> headlineNewsPageVos;
        headlineNewsPageVos = headlineNewsIPage.getRecords().stream().map(headlineNews -> {
            return BeanUtil.copyProperties(headlineNews, HeadlineNewsPageVo.class);
        }).collect(Collectors.toList());
        headlineNewsPageVoIPage.setRecords(headlineNewsPageVos);
        headlineNewsPageVoIPage.setTotal(headlineNewsIPage.getTotal());
        return headlineNewsPageVoIPage;
    }

    /**
     * 头条新闻详情
     *
     * @param uuid
     * @return
     */
    @Override
    public HeadlineNewsVo detail(String uuid) {
        HeadlineNews headlineNews = headlineNewsMapper.findById(uuid)
            .orElseThrow(() -> new BusinessException("头条新闻不存在"));
        return BeanUtil.copyProperties(headlineNews, HeadlineNewsVo.class);
    }
}
